package gpstools.data;

import generated.gpx.ExtensionsType;
import generated.gpx.TrackPointExtensionT;
import generated.gpx.WptType;
import gpstools.Point;
import gpstools.track.TrackPoint;
import gpstools.track.TrackPoint.Builder;

import javax.xml.bind.JAXBElement;

class GpxConverter {
    static TrackPoint pointFromGpx(WptType gpx) {
        /* standard, required */
		if (gpx == null || gpx.getLat() == null || gpx.getLon() == null) {
            return null;
        }
        final double lon = gpx.getLon().doubleValue();
        final double lat = gpx.getLat().doubleValue();

		final Double ele = gpx.getEle() != null ? gpx.getEle().doubleValue()
			: null;

        final long time;
        if (gpx.getTime() != null)
            time = gpx.getTime().toGregorianCalendar().getTimeInMillis();
        else
            time = 0;

        Builder builder = TrackPoint.builder(new Point(lat, lon, ele)).time(time);
        /* extensions, optional */

        ExtensionsType extensions = gpx.getExtensions();
        if (extensions != null) {
            processExtensions(builder, extensions);
        }

        return builder.build();
    }

    private static void processExtensions(Builder builder, ExtensionsType extensions) {
        for (Object extension : extensions.getAny()) {
            if (extension instanceof JAXBElement<?>) {
                JAXBElement<?> element = (JAXBElement<?>) extension;
                if (element.getValue() instanceof TrackPointExtensionT) {
                    /* garmin track point v1 extension */
                    TrackPointExtensionT ext = (TrackPointExtensionT) element.getValue();
                    if (ext.getHr() != null) {
                        builder.heartRate(ext.getHr());
                    }
                    if (ext.getCad() != null) {
                        builder.cadence(ext.getCad());
                    }
                }
            }
        }
    }

}
